package com.hnchances.studentscoresystem.config;

import com.hnchances.studentscoresystem.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;


import java.io.IOException;
import java.util.Collections;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;

    public JwtAuthenticationFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            // 1. 从Header获取Token
            String token = request.getHeader("Authorization");
            if (token == null || token.trim().isEmpty()) {
                filterChain.doFilter(request, response);
                return;
            }

            // 2. 验证Token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token已过期，请重新登录");
                return;
            }

            // 3. 解析Token获取用户信息
            Claims claims = jwtUtil.parseToken(token);
            Long userId = claims.get("userId", Long.class);
            String userName = claims.get("userName", String.class);
            Integer identity = claims.get("identity", Integer.class);

            // 4. 构建Authentication对象并设置到SecurityContext
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userName, null, Collections.emptyList()
            );
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 5. 将用户信息设置到Request属性中（便于后续业务使用）
            request.setAttribute("userId", userId);
            request.setAttribute("userName", userName);
            request.setAttribute("identity", identity);
        } catch (Exception e) {
            log.error("JWT认证失败", e);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "认证失败，请重新登录");
            return;
        }

        // 6. 继续执行过滤链
        filterChain.doFilter(request, response);
    }
}